//
//  KSPageSwitchView.swift
//  Merchant
//
//  Created by liuxm on 2017/8/11.
//  Copyright © 2017年 huanniu. All rights reserved.
//

import UIKit

protocol KSPageSwitchViewDelegate: NSObjectProtocol {
    // 0代表第一页点击 1代表第二页 2...
    func pageSwitchClick(page: Int)
}

fileprivate let kLineWidth:CGFloat = 65

/// 页面切换 针对一个Controller 多个页面切换
class KSPageSwitchView: UIView {

    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */
    // 按钮项目
    fileprivate var itemArray:Array<Any>!
    fileprivate var lineView:UIView!
    fileprivate var itemWidth:CGFloat!
    // 选择页面
    fileprivate var selectPage = 0
    // 动画
    fileprivate var displayLink:CADisplayLink! = nil
    
    weak var delegate:KSPageSwitchViewDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    func initView(item:Array<String>) {
        self.itemArray = Array(item)
        
        let count = item.count
        if count > 0 {
            itemWidth = KSConstants.kScreenWidth/CGFloat(count)
            for i in 0 ..< count {
                let itemBtn = UIButton(frame: CGRect(x: itemWidth * CGFloat(i), y: 0, width: self.itemWidth, height: self.frame.height))
                itemBtn.setTitleColor(KSColor.kColor_3, for: UIControlState.normal)
                itemBtn.setTitleColor(UIColor.colorWithHexString(hex: "dd2727"), for: UIControlState.selected)
                itemBtn.addTarget(self, action:#selector(KSPageSwitchView.pageBtnClick(sender:)), for: UIControlEvents.touchUpInside)
                itemBtn.titleLabel?.font = KSMacro.FontBySize(size: 16)
                itemBtn.setTitle(item[i], for: UIControlState.normal)
                itemBtn.tag = 100 + i
                self.addSubview(itemBtn)
                if i == 0 {
                    itemBtn.isSelected = true
                    
                    self.lineView = UIView(frame: CGRect(x: (self.itemWidth - kLineWidth)/2, y: frame.height - 1, width: kLineWidth, height: 1))
                    self.lineView.backgroundColor = UIColor.red
                    self.addSubview(self.lineView)
                }
            }
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc fileprivate func pageBtnClick(sender:UIButton) {
        let page = sender.tag - 100
        self.delegate?.pageSwitchClick(page: page)
        
        let count = self.itemArray.count
        for i in 0 ..< count {
            if page == i {
                selectPage = page
                sender.isSelected = true
                self.startAnimation()
            } else {
                let btn = self.viewWithTag(i + 100) as! UIButton
                btn.isSelected = false
            }
        }
    }
    
    fileprivate func startAnimation() {
        if self.displayLink == nil {
            self.displayLink = CADisplayLink(target: self, selector: #selector(KSPageSwitchView.displayLinkAction(disp:)))
            self.displayLink.add(to:RunLoop.main, forMode: RunLoopMode.commonModes)
        }
    }
    
    fileprivate func stopAnimation() {
        if self.displayLink != nil {
            self.displayLink.invalidate()
            self.displayLink = nil
        }
    }
    
    @objc fileprivate func displayLinkAction(disp:CADisplayLink) {
        UIView.animate(withDuration: 0.5, animations: {
            self.lineView.frame = CGRect(x: self.itemWidth*CGFloat(self.selectPage) + (self.itemWidth - kLineWidth)/2, y: self.frame.height - 1, width: kLineWidth, height: 1)
            self.layoutIfNeeded()
        }) { (finished:Bool) in
            if finished {
                self.stopAnimation()
            }
        }
    }
}
